package org.dim.oa.exception;

import org.dim.oa.po.ServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.nio.file.AccessDeniedException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * Spring security权限不足处理类
     * 只有登录后（即接口有传token）接口权限不足才会进入AccessDeniedHandler，
     * 如果是未登陆或者会话超时等，不会触发AccessDeniedHandler，而是会直接跳转到登陆页面。
     */
     //会执行该方法
    @ExceptionHandler(AccessDeniedException.class)
    public ServerResponse handleAccessDeniedException(HttpServletRequest req, AccessDeniedException e){
        log.error(e.getMessage(), e);
        return ServerResponse.fail(ServerResponse.UNAUTH, ("权限不足"));
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ServerResponse handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return ServerResponse.fail(ServerResponse.BAD_PARAMETER, ("不支持' " + e.getMethod() + "'请求"));
    }

    /**
     * 全局拦截就不需要有运行时异常拦截和中国类拦截，这样时没有意义的，你就应该写一个很拦截异常处理，不然不如向AccessDeniedException它就不会
     */
    /**
     * 拦截未知的运行时异常
     */
//    @ExceptionHandler(RuntimeException.class)
//    public ServerResponse notFount(RuntimeException e) {
//        log.error("运行时异常:", e);
//        return ServerResponse.fail(ServerResponse.INNER_ERROR, "运行时异常:" + e.getMessage());
//    }

    /**
     * 系统异常
     */
//    @ExceptionHandler(Exception.class)
//    public ServerResponse handleException(Exception e) {
//        log.error(e.getMessage(), e);
//        if (e instanceof RuntimeException){
//            log.error(e.getMessage(), e);
//            return ServerResponse.fail(ServerResponse.UNAUTH, ("权限不足"));
//        }
//        return ServerResponse.fail(ServerResponse.INNER_ERROR, "服务器错误，请联系管理员");
//    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ServerResponse exceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + ";";
        }
        return ServerResponse.fail(ServerResponse.BAD_PARAMETER, errorMesssage);
    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = BindException.class)
    public ServerResponse validationExceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + ";";
        }
        return ServerResponse.fail(ServerResponse.BAD_PARAMETER, errorMesssage);
    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ServerResponse ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        return ServerResponse.fail(ServerResponse.BAD_PARAMETER, String.join(",", msgList));
    }

    /**
     * 业务异常
     */
   /* @ExceptionHandler(BusinessException.class)
    public AjaxResult businessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }
*/
    /**
     * 演示模式异常
     */
    /*@ExceptionHandler(DemoModeException.class)
    public AjaxResult demoModeException(DemoModeException e) {
        return AjaxResult.error("演示模式，不允许操作");
    }*/

}
